package com.itmate.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itmate.entity.Users;
import com.itmate.service.UsersService;



/**
 * Servlet implementation class DoRegister
 */
@WebServlet("/doregister")
public class DoRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoRegister() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		  request.setCharacterEncoding("utf-8");
	        String error="";
			String username = request.getParameter("User_name");
			String sex=request.getParameter("User_sex");
			String password = request.getParameter("password");
			String password2 = request.getParameter("password2");	
			//添加用户
			Users mu = new Users();	
			mu.setUser_name(username);
			mu.setSex(sex);
			mu.setPassword(password);
			
			UsersService mus = new UsersService();
		    	
			boolean bl = mus.isExist(mu);
			if(bl) {
				error="用户名已存在";
				request.setAttribute("error",error);
				request.getRequestDispatcher("/WEB-INF/jsp/Error.jsp").forward(request, response);
				System.out.print("用户名已存在");
			}else if(!password.equals(password2)){
				error="两次密码不一致";
				request.setAttribute("error",error);
				request.getRequestDispatcher("/WEB-INF/jsp/Error.jsp").forward(request, response);
			}else{
				int i = mus.addUser(mu);
				if(i == 1) {
					System.out.print("注册成功");
					request.getRequestDispatcher("/WEB-INF/jsp/Login.jsp").forward(request, response);
				}else {
					error="注册失败";
					request.setAttribute("error",error);
					request.getRequestDispatcher("/WEB-INF/jsp/Error.jsp").forward(request, response);
				
				}
			}
		
	}

}
